package cn.nexd.task;

/**
 * AsyncTaskTestCase create by codingfish at 15/5/25
 * TODO:
 *
 * @Version V1.0
 */

import android.os.SystemClock;

import junit.framework.TestCase;

import java.util.Arrays;

/**
 * AsyncTaskTestCaseImpl create by codingfish at 15/3/26
 * TODO:
 *
 * @Version V1.0
 */
public class AsyncTaskTestCase extends TestCase {
    @Override
    public void setUp() throws Exception {
        super.setUp();
    }

    //测试较大量的并发,允许任务丢失.
    public void testAsyncTaskAllowingLossByAsyncTask() throws Exception {
        // 只有一个任务
        AsyncTask<Void, Void, Void> task_one = new AsyncTask<Void, Void, Void>() {
            @Override
            protected Void doInBackground(Void... params) {
                Log.i("One AsyncTask Execute");
                return null;
            }
        };
        task_one.execute();
        // 休眠3秒，给 Log 预留出时间
        SystemClock.sleep(3 * 1000);
        // 多个任务
        for (int i = 0; i <= 100; i++) {
            final int a = i;
            AsyncTask task_more = new AsyncTask() {
                @Override
                protected Object doInBackground(Object[] params) {
                    Log.i("AsyncTask executeAllowingLoss " + a);
                    SystemClock.sleep(1 * 1000);
                    return null;
                }
            };
            task_more.executeAllowingLoss();
        }
        //休眠 30 秒，留给线程池执行时间
        SystemClock.sleep(30 * 1000);
    }

    //测试较大量的并发,允许任务丢失.
    public void testAsyncTaskAllowingLossByRunnable() throws Exception {
        AsyncTask.execute(new Runnable() {
            @Override
            public void run() {
                Log.i("One AsyncTask Execute");
            }
        });
        SystemClock.sleep(3 * 1000);
        for (int i = 0; i <= 100; i++) {
            final int a = i;
            AsyncTask.executeAllowingLoss(new Runnable() {
                @Override
                public void run() {
                    Log.i("AsyncTask executeAllowingLoss " + a);
                    SystemClock.sleep(1 * 1000);
                }
            });
        }
        SystemClock.sleep(30 * 1000);
    }

    //测试 SampleTask。仅仅指定返回结果的类型，不可输入参数
    public void testSampleTask() throws Exception {
        SimpleTask<Double> simpleTask = new SimpleTask<Double>() {
            @Override
            protected Double doInBackground() {
                return Math.random();
            }

            @Override
            protected void onPostExecute(Double result) {
                super.onPostExecute(result);
                Log.i("SimpleTask result: " + result);
            }
        };
        simpleTask.execute();
        SystemClock.sleep(30 * 1000);
    }

    //测试 SampleSafeTask。仅仅指定返回结果的类型，不可输入参数
    public void testSampleSafeTask() throws Exception {
        SimpleSafeTask<String> simpleSafeTask = new SimpleSafeTask<String>() {
            @Override
            protected String doInBackgroundSafely() throws Exception {
                return "HelloWorld";
            }

            @Override
            protected void onPostExecuteSafely(String result, Exception e) throws Exception {
                super.onPostExecuteSafely(result, e);
                Log.i("SimpleSafeTask onPostExecuteSafely " + result
                        + " , thread id  : " + Thread.currentThread().getId());
            }
        };
        simpleSafeTask.execute();
        SystemClock.sleep(3 * 1000);
        // 测试异常抛出
        SimpleSafeTask simpleSafeTaskWithException = new SimpleSafeTask() {
            @Override
            protected Object doInBackgroundSafely() throws Exception {
                Log.i("SimpleSafeTask : doInBackground");
                String string = null;
                string.toCharArray();
                return null;
            }

            @Override
            protected void onPostExecuteSafely(Object o, Exception e) throws Exception {
                super.onPostExecuteSafely(o, e);
                Log.i("SimpleSafeTask : onPostExecuteSafely, exception: " + e);
                String string = null;
                string.toCharArray();
            }

            @Override
            protected void onPreExecuteSafely() throws Exception {
                super.onPreExecuteSafely();
                Log.i("SimpleSafeTask : onPreExecuteSafely");
                String string = null;
                string.toCharArray();
            }
        };
        simpleSafeTaskWithException.execute();
        SystemClock.sleep(30 * 1000);
    }

    //安全异步任务，可以捕获任意异常，并反馈给给开发者。
    public void testSafeTask() throws Exception {
        SafeTask<Integer, Integer, String> safeTask = new SafeTask<Integer, Integer, String>() {
            @Override
            protected String doInBackgroundSafely(Integer... params) throws Exception {
                Log.i("SafeTask error doInBackgroundSafely, thread id  : "
                        + Thread.currentThread().getId());
                publishProgress(1, 2, 3);
                String s = null;
                s.toCharArray();
                return null;
            }

            @Override
            protected void onPreExecuteSafely() throws Exception {
                super.onPreExecuteSafely();
                Log.i("SafeTask error onPreExecuteSafely, thread id  : "
                        + Thread.currentThread().getId());
                String s = null;
                s.toCharArray();
            }

            @Override
            protected void onPostExecuteSafely(String result, Exception e) throws Exception {
                super.onPostExecuteSafely(result, e);
                Log.i("SafeTask error onPostExecuteSafely :" + result
                        + ",  thread id  : " + Thread.currentThread().getId());
                Log.i("SafeTask error onPostExecuteSafely Exception :" + e
                        + ",  thread id  : " + Thread.currentThread().getId());
                String s = null;
                s.toCharArray();
            }

            @Override
            protected void onProgressUpdateSafely(Integer... values) throws Exception {
                super.onProgressUpdateSafely(values);
                Log.i("SafeTask error onProgressUpdateSafely :"
                        + Arrays.toString(values) + ",  thread id  : "
                        + Thread.currentThread().getId());
                String s = null;
                s.toCharArray();
            }
        };
        safeTask.execute();
        SystemClock.sleep(30 * 1000);
    }

    //测试延时取消（500ms）之后取消
    public void testCancelDelay() throws Exception {
        SimpleTask<Integer> simpleTask = new SimpleTask<Integer>() {
            @Override
            protected Integer doInBackground() {
                try {
                    Thread.sleep(1500);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                return 1;
            }

            @Override
            protected void onPostExecute(Integer result) {
                super.onPostExecute(result);
                Log.i("SimpleTask execute : " + result);
            }

            @Override
            protected void onCancelled() {
                super.onCancelled();
                Log.i("SimpleTask onCancelled  ");
            }
        };
        simpleTask.execute();
        SystemClock.sleep(500);
        simpleTask.cancel(true);
        SystemClock.sleep(30 * 1000);
    }

    //测试顺序执行的 TaskExecutor。按照 task3-task1-task2的顺序执行
    public void testOrderedTaskExecutor() throws Exception {
        SimpleTask<Integer> task1 = getTask(1);
        SimpleTask<Integer> task2 = getTask(2);
        SimpleTask<Integer> task3 = getTask(3);
        TaskExecutor.newOrderedExecutor().put(task3).put(task1).put(task2).start();
        SystemClock.sleep(30 * 1000);
    }

    //测试并发以及等待执行的 TaskExecutor,task1 task2 task3 并发执行，destTask 最后执行
    public void testCyclicBarrierExecutor() throws Exception {
        SimpleTask<?> task1 = getTask(1);
        SimpleTask<?> task2 = getTask(2);
        SimpleTask<?> task3 = getTask(3);
        final long startTime = System.currentTimeMillis();
        SimpleTask<String> destTask = new SimpleTask<String>() {
            @Override
            protected String doInBackground() {
                return "This is the destination. You can do anything you want.";
            }

            @Override
            protected void onPostExecute(String result) {
                Log.i("CyclicBarrierExecutor use time: "
                        + (System.currentTimeMillis() - startTime)
                        + " , info: " + result);
            }
        };
        // task 1,2,3 execute concurrently. destTask is the destination task.
        // 123并发执行，全部完成后，执行destTask。
        TaskExecutor.newCyclicBarrierExecutor().put(task1).put(task2)
                .put(task3).start(destTask);
//        task2.cancel(true);
    }

    @Override
    public void tearDown() throws Exception {
        super.tearDown();
    }

    private SimpleTask<Integer> getTask(final int id) {
        SimpleTask<Integer> simple = new SimpleTask<Integer>() {
            @Override
            protected Integer doInBackground() {
                try {
                    Thread.sleep(1000 * id);
                } catch (InterruptedException e) {
                }
                return id;
            }

            @Override
            protected void onCancelled() {
                Log.i("SimpleTask onCancelled : " + id);
            }

            @Override
            protected void onPostExecute(Integer result) {
                Log.i("SimpleTask execute : " + result);
            }
        };
        return simple;
    }
}